package com.fudan.backend.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fudan.backend.exception.BaseException;
import com.fudan.backend.pojo.statics.UserRole;
import com.fudan.backend.exception.RetCode;
import com.fudan.backend.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class SellerInterceptor implements HandlerInterceptor {
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        response.setCharacterEncoding("UTF-8");
        int role = JwtUtil.getRole(token);

        if(role != UserRole.Admin && role != UserRole.Seller){//非商户且不是管理员
            throw new BaseException(RetCode.UNAUTHORIZED_REQUEST.getCode(), RetCode.UNAUTHORIZED_REQUEST.getMessage());
        }
        return true;
    }
}
